package cn.mygweb.admin.modules.sys.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;

import cn.mygweb.admin.modules.sys.pojo.User;
import cn.mygweb.admin.modules.sys.pojo.UserRole;
import cn.mygweb.common.controller.BaseController;
import cn.mygweb.common.pojo.JsonResult;
import cn.mygweb.common.utils.UploadUtils;
import lombok.extern.slf4j.Slf4j;

/** 
* <p>Title: SysUserController.java</p>
* <p>Description: 系统用户管理</p>  
* @author gxb 
* @date 2019年6月1日 
* <p>Copyright: Copyright (c) 2019</p>
* <p>Company: www.mygweb.cn</p> 
*/
@Controller
@RequestMapping("/admin/sys/user")
@Slf4j
public class UserController extends BaseController{

	@Value("${pagehelper.pageSize}")
	private Integer pageSize;
	
	//文件上传地址
	@Value("${file.upload.path}")
	private String uploadFilePath;
	
	/**
	 * <p>Title: setLoginUser</p>
	 * <p>Description: 设置当前登录用户信息</p>
	 * @return
	 */
	@RequestMapping("/setLoginUser")
	@ResponseBody
	public JsonResult setLoginUser() {
		Subject subject = SecurityUtils.getSubject();
		User user = (User)subject.getPrincipal();
		return JsonResult.ok(user);
	}
	
	/**
	 * <p>Title: allUsers</p>
	 * <p>Description: 系统用户管理页面，分页查看，每页显示条数根据application.properties文件中的配置数量决定</p>
	 * @param model
	 * @param pageNum
	 * @return
	 */
	@RequestMapping("/userList")
	public String allUsers(ModelMap model, Integer pageNum) {
		if(pageNum == null || pageNum < 1) {
			pageNum = 1;
		}
		User user = new User();
		Integer pageSize = this.pageSize;
		Integer count = userService.selectCount(user);
		Integer totalPages = count % pageSize == 0 ? (count / pageSize) : (count / pageSize + 1);
		model.addAttribute("totalPages", totalPages);
		if(pageNum > totalPages) {
			pageNum = totalPages;
		}
		List<User> userList = userService.queryUserListPaged(user, pageNum, pageSize);
		model.addAttribute("userList", userList);
		model.addAttribute("currentPage", pageNum);
		model.addAttribute("pageSize", pageSize);
		return "admin/modules/sys/user";
	}
	
	/**
	 * <p>Title: userAlreadyExists</p>
	 * <p>Description: 异步判断用户是否已经存在</p>
	 * @param user
	 * @return
	 */
	@RequestMapping("/userAlreadyExists")
	@ResponseBody
	public JsonResult userAlreadyExists(User user) {
		if(userService.userAlreadyExists(user)) 
			return JsonResult.errorMsg("用户名已存在");
		return JsonResult.ok("用户名可以使用");
	}
	
	/**
	 * <p>Title: ajaxUserInfo</p>
	 * <p>Description: 异步获取用户信息</p>
	 * @param userId
	 * @return
	 */
	@RequestMapping("/ajaxUserInfo")
	@ResponseBody
	public JsonResult ajaxUserInfo(String userId) {
		User user = userService.findById(userId);
		return JsonResult.ok(user);
	}
	
	/**
	 * <p>Title: saveUser</p>
	 * <p>Description: 添加用户信息</p>
	 * @param user
	 * @param role
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public JsonResult saveUser(User user, String role) {
		try {
			//1.验证用户名是否存在.如果存在，返回错误信息
			if(userService.userAlreadyExists(user)) {
				return JsonResult.errorMsg("用户名已存在");
			}
			//2.如果不存在，插入用户信息并返回正确信息
			String id = sid.nextShort();
			user.setId(id);
			user.setRegistTime(new Date());
			//插入用户信息
			userService.insert(user);
			updateUserRole(user, role);//更新用户角色信息	
			this.delAllRedisCache();
			return JsonResult.ok("添加成功");
		} catch (Exception e) {
			e.printStackTrace();
			return JsonResult.errorMsg("添加失败");
		}
	}
	
	/**
	 * <p>Title: updateUserRole</p>
	 * <p>Description: 删除用户的角色信息，然后重新插入用户-角色信息</p>
	 * @param user
	 * @param role
	 */
	public void updateUserRole(User user, String role) {
		if(role != null && !StringUtils.isEmptyOrWhitespace(role)) {
			userRoleService.batchDeleteByUId(user.getId());//首先删除
			List<UserRole> urList = new ArrayList<UserRole>();
			for (String rid : role.split(",")) {
				UserRole ur = new UserRole();
				ur.setId(sid.nextShort());
				ur.setUid(user.getId());
				ur.setRid(rid);
				urList.add(ur);
			}
			userRoleService.insertURList(urList);
		}
	}
	
	/**
	 * <p>Title: deleteById</p>
	 * <p>Description: 删除用户信息</p>
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public JsonResult delete(String id) {
		try {
			userService.deleteUser(id);
			this.delAllRedisCache();
			return JsonResult.ok("删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			return JsonResult.errorMsg("删除失败");
		}
	}
	
	/**
	 * <p>Title: update</p>
	 * <p>Description: 更新用户信息</p>
	 * @param user
	 * @param role
	 * @return
	 */
	@RequestMapping("/update")
	@ResponseBody
	public JsonResult update(User user, String role) {
		try {
			if(null != user.getId()) {
				if(userService.userAlreadyExists(user)) {
					return JsonResult.errorMsg("用户名已存在");
				}
				userService.updateUser(user);
				updateUserRole(user, role);
				this.delAllRedisCache();
				return JsonResult.ok("修改成功");
			}else {
				return JsonResult.errorMsg("修改失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return JsonResult.errorMsg("修改失败");
		}
	}
	
	@RequestMapping("/disable")
	@ResponseBody
	public JsonResult disable(String id) {
		try {
			User user = userService.findById(id);
			user.setStatus(2);
			userService.updateUser(user);
			this.delAllRedisCache();
			return JsonResult.ok("操作成功");
		} catch (Exception e) {
			e.printStackTrace();
			return JsonResult.errorMsg("操作失败");
		}
	}
	
	/**
	 * <p>Title: upload</p>
	 * <p>Description: 上传文件（头像）</p>
	 * @param file
	 * @param userId
	 * @return
	 */
	@RequestMapping("/uploadFaceImage")
	@ResponseBody
	public JsonResult upload(@RequestParam("file") MultipartFile file, String userId) {
		if(file.isEmpty()) {
			return JsonResult.errorMsg("上传失败，请选择文件");
		}
		try {
			String afterUploadPath = UploadUtils.uploadImg(file, uploadFilePath);
			//修改用户的头像信息
			User user = userService.findById(userId);
			user.setFaceImage(afterUploadPath);
			userService.updateUser(user);
			this.delAllRedisCache();
			return JsonResult.build(200, "头像上传成功", afterUploadPath);
		} catch (Exception e) {
			e.printStackTrace();
			return JsonResult.errorMsg("头像上传失败");
		}
	}
	
}
